//
//  CMDBHttpManager.swift
//  CMDB
//
//  Created by 王磊 on 17/4/5.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit
class CMDBSessionManager: NSObject {
    
    class func getInstance() -> AFHTTPSessionManager {
        struct Singleton{
            static var onceToken : dispatch_once_t = 0
            static var single:AFHTTPSessionManager?
        }
        dispatch_once(&Singleton.onceToken,{
            Singleton.single = AFHTTPSessionManager()
            }
        )
        return Singleton.single!
    }
}

class CMDBHttpManager: NSObject {
    
    static let getInstance: CMDBHttpManager = CMDBHttpManager()
    
    private override init() {
        super.init()
        
    }
}

extension CMDBHttpManager: CMDBHttpManagerDelegate {
    
    func netWorkReachability(url: String) -> Bool {
        
        var netState = false
        
        let baseUrl = NSURL(string: url)
        
        let manager = AFHTTPSessionManager(baseURL: baseUrl)
        
        _ = manager.operationQueue
        
        manager.reachabilityManager.setReachabilityStatusChangeBlock { (status) in
            
            switch status {
            case .ReachableViaWWAN:
                fallthrough
            case .ReachableViaWiFi:
                
                netState = true
            case .NotReachable:
                
                netState = false
            default:
                
                break
            }
        }
        
        manager.reachabilityManager.startMonitoring()
        
        return netState
    }
    
    func queryToken() -> String {
        
        return CMDBApplicationManager.getInstance.querryToken()
        
    }
    func request(url: String, param: Dictionary<String, AnyObject>?, success: CMDBHttpSuccessHandler,error: CMDBHttpErrorHandler, failure: CMDBHttpFailureHandler) {
        
        //        if !netWorkReachability(url) {
        //
        //            failure()
        //
        //            return
        //        }
        
        let mutableParams: NSMutableDictionary = NSMutableDictionary()
        
        if let tempParam = param {
            
            mutableParams.addEntriesFromDictionary(tempParam)
        }
        let token: String = queryToken()
        
        if !token.isEmpty {
            
            mutableParams.setValue(token, forKey: "token")
        }
        
        CMDBSessionManager.getInstance().requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
        
        CMDBSessionManager.getInstance().POST(url, parameters: mutableParams, progress: { (progress) in
            
            
            }, success: { (dataTask, responseObject) in
                if let _ = responseObject where NSJSONSerialization.isValidJSONObject(responseObject!) {
                    
                    let baseBean = CMDBBaseBean.objectWithKeyValues(responseObject as! NSDictionary) as! CMDBBaseBean
                    
                    if baseBean.serviceCode == CMDBRescodeType.Success {
                        
                        success(sysTime: baseBean.sysTime,data: baseBean.data,page: baseBean.page)
                        
                    } else if baseBean.serviceCode == CMDBRescodeType.Mutex{
                        
                        error(rescode: baseBean.serviceCode)
                        
                        CMDBShowInfoManager.getInstance.showInfoWithStatus("您的登录已过期")
                        
                        UIApplication.sharedApplication().keyWindow?.rootViewController =  CustomNavigationControllerViewController(rootViewController: CMDBLoginViewController(), hideNavBar: true)
                        
                    }else {

                        error(rescode: baseBean.serviceCode)

                    }
                }
                
        }) { (dataTask, error) in
            
            failure()
        }
    }

}
extension CMDBHttpManager {
    
    func request(url: String, param: Dictionary<String, AnyObject>?, ownPage: Int, tableView: UITableView, success: CMDBHttpSuccessHandler, error: CMDBHttpErrorHandler, failure: CMDBHttpFailureHandler) {
        
        //        if !netWorkReachability(url) {
        //
        //            failure()
        //
        //            return
        //        }
        
        let mutableParams: NSMutableDictionary = NSMutableDictionary()
        
        if let tempParam = param {
            
            mutableParams.addEntriesFromDictionary(tempParam)
        }
        
        mutableParams.setValue("\(ownPage)", forKey: "page")
        
        let token: String = queryToken()
        
        if !token.isEmpty {
            
            mutableParams.setValue(token, forKey: "token")
        }
        
        var mjComponent: MJRefreshComponent?
        
        if let header = tableView.mj_header,footer = tableView.mj_footer {
            
            mjComponent = ownPage == 0 ? header : footer
        }
        
        CMDBSessionManager.getInstance().requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
        
        CMDBSessionManager.getInstance().POST(url, parameters: mutableParams, progress: { (progress) in
            
            
            }, success: { (dataTask, responseObject) in
                if let _ = responseObject where NSJSONSerialization.isValidJSONObject(responseObject!) {
                    
                    let baseBean = CMDBBaseBean.objectWithKeyValues(responseObject as! NSDictionary) as! CMDBBaseBean
                    
                    if baseBean.serviceCode == CMDBRescodeType.Success {
                        
                        success(sysTime: baseBean.sysTime,data: baseBean.data,page: baseBean.page)
                        
                    } else if baseBean.serviceCode == CMDBRescodeType.Mutex{
                        
                        error(rescode: baseBean.serviceCode)
                        
                        CMDBShowInfoManager.getInstance.showInfoWithStatus("您的登录已过期")
                        
                        UIApplication.sharedApplication().keyWindow?.rootViewController =  CustomNavigationControllerViewController(rootViewController: CMDBLoginViewController(), hideNavBar: true)
                        
                    }else {
                        
                        error(rescode: baseBean.serviceCode)
                        
                        printLog(baseBean.msg)
                    }
                    
                    if let mjComponent = mjComponent {
                        
                        mjComponent.endRefreshing()
                    }
                    
                }
                
        }) { (dataTask, error) in
            
            failure()
            
            if let mjComponent = mjComponent {
                
                mjComponent.endRefreshing()
            }
        }
        
        
    }
}


